import { WsClient, WsConnection, WsServer } from "tsrpc";
import { v4 } from "uuid";
import { getGameConfig } from "./gameConfigMgr";
import { serviceProto as GameServiceProto, ServiceType as GameServiceType } from "./shared/gameClient/protocols/serviceProto";
import { logger } from "./shared/tsgf/logger";
import { GameConnMgr } from "./GameConnMgr";
import { ClusterNodeClient } from "./shared/tsgfServer/cluster/ClusterNodeClient";
import { IGameServerInfo } from "./shared/gateClient/GameServer";

/**游戏服务端的客户端连接*/
export type ClientConnection = WsConnection<GameServiceType>;
export type GameServer = WsServer<GameServiceType>;

/**拓展字段*/
declare module 'tsrpc' {
    export interface BaseConnection {
        /**连接ID,连接在服务端唯一标识*/
        connectionId: string;
    }
}

var serverCfg = getGameConfig();

//==========================================================
// 游戏服务
//==========================================================
/**全局唯一的游戏服务对象*/
export const gameServer: GameServer = new WsServer(GameServiceProto, {
    port: serverCfg.gameServer.listenPort,
    json: false,
    logger: logger,
});
//设置游戏服务连接ID
gameServer.flows.postConnectFlow.push(async v => {
    v.connectionId = v4();
    return v;
});
//初始化游戏连接管理器
export const gameConnMgr = new GameConnMgr(gameServer);




//==========================================================
// 游戏服务器集群
//==========================================================

/**全局唯一的游戏服务器集群客户端*/
export const gameClusterClient = new ClusterNodeClient<IGameServerInfo>(
    serverCfg.gameServer.gameClusterServerWSUrl,
    serverCfg.gameServer.serverId, serverCfg.gameServer.clusterKey, () => {
        return {
            serverId: serverCfg.gameServer.serverId,
            serverName: serverCfg.gameServer.serverName,
            serverWSUrl: serverCfg.gameServer.serverWSUrl,
            clientCount: gameServer.connections.length,
            extendData: serverCfg.gameServer.extendData,
        };
    });
